package admin.auth.service.impl;


import admin.auth.domain.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;
import admin.common.constant.MessageConstant;
import admin.common.domain.Client;
import admin.common.domain.dto.UserDto;
import admin.common.domain.req.Oauth2LoginReq;
import admin.common.properties.OauthProperties;
import admin.common.utils.FieldUtil;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理业务类
 * Created by zgb on 2020/6/19.
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    /**
     * 上下文对象实例
     */
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private HttpServletRequest request;


    @Autowired
    private OauthProperties oauthProperties;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String currentClientId = request.getParameter(FieldUtil.getField(Oauth2LoginReq::getClient_id).getName());
        List<Client> clients = oauthProperties.getClients();
        Client currentClient = clients.stream().filter(e -> e.getId().equals(currentClientId)).findFirst().orElse(null);
        UserDto userDto = null;
        //不同的端有不同的查询
        Class<?> aClass = null;
        try {
            aClass = Class.forName(currentClient.getClassOfLoadUserByUsername());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        String canonicalName = aClass.getCanonicalName();
        String methodName = currentClient.getMethodOFLoadUserByUsername();
        /*通过Class对象来获取对象中的方指定法
         *第一个参数是class对象，第二个参数是方法名
         *第三个参数是可变参数(根据需求可传可不传)，需要传入参数的类型class对象(eg:String.class)
         */
        Method method = Arrays.stream(applicationContext.getBean(canonicalName).getClass().getMethods()).filter(m->m.getName().equals(methodName)).collect(Collectors.toList()).get(0);
        /*
         *执行方法
         *第一个参数是Method 对象，第二个参数是对象
         *第三个参数是可变参数(根据需求可传可不传)，需要传入调用方法的参数值
         */
        userDto =(UserDto)  ReflectionUtils.invokeMethod(method,applicationContext.getBean(canonicalName),new Object[]{username});
        if (userDto==null) {
            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        userDto.setClientId(currentClientId);
        SecurityUser securityUser = new SecurityUser(userDto);
        if (!securityUser.isEnabled()) {
            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }

}
